package com.example.chamberlainserver.security;

import com.example.chamberlainserver.Service.TokenValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT请求过滤器，用于拦截请求并验证JWT令牌
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private TokenValidationService tokenValidationService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {


        String path = request.getRequestURI();

        final String requestTokenHeader = request.getHeader("Authorization");
        String jwtToken = tokenValidationService.extractTokenFromHeader(requestTokenHeader);

        if (path.equals("/auth/login") || path.equals("/auth/register") || path.equals("/auth/logout") || path.equals("/auth/sendSmsCode") || path.equals("/auth/loginByPhone")) {
            System.out.println("JwtRequestFilter: 放行请求 - " + path);
            chain.doFilter(request, response);
            return;
        }

        if (jwtToken == null) {
            System.out.println("JwtRequestFilter: 请求 " + path + " 缺少有效的Authorization头");
            chain.doFilter(request, response);
            return;
        }

        String username = null;
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
        } catch (Exception e) {
            System.out.println("JwtRequestFilter: JWT Token解析失败 - " + e.getMessage());
            chain.doFilter(request, response);
            return;
        }

        // 验证token
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            System.out.println("JwtRequestFilter: 验证用户 " + username + " 的token");

            // 首先检查token是否过期
            if (!tokenValidationService.isTokenNotExpired(jwtToken)) {
                System.out.println("JwtRequestFilter: 用户 " + username + " 的token已过期");
                // token已过期，不设置认证信息，让后续的TokenValidationAspect处理
                chain.doFilter(request, response);
                return;
            }

            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);

            // 如果token有效，则配置Spring Security使用该token
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 设置当前用户为已认证状态
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                System.out.println("JwtRequestFilter: 用户 " + username + " 的token有效，已设置认证状态");
            } else {
                System.out.println("JwtRequestFilter: 用户 " + username + " 的token无效");
                // token无效，不设置认证信息，让后续的TokenValidationAspect处理
            }
        } else if (username == null) {
            System.out.println("JwtRequestFilter: 无法从token中提取用户名");
        } else {
            System.out.println("JwtRequestFilter: 用户已认证，跳过token验证");
        }

        chain.doFilter(request, response);
    }
}